package com.wtpaint.udp.test1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * UDP搜索放，用于搜索
 */
public class UDPSearcher {

    public static void main(String[] args) throws IOException {
        System.out.println("UDPSearcher started.");
        //作为搜索方系统自动分配端口
        DatagramSocket ds = new DatagramSocket();

        //构建发送数据
        String responseData = " Hello World !";
        byte[] responseBytes = responseData.getBytes();
        DatagramPacket requestPack = new DatagramPacket(responseBytes,
                responseBytes.length);
        //发送给本机地址
        requestPack.setAddress(InetAddress.getLocalHost());
        requestPack.setPort(20001);
        //发送
        ds.send(requestPack);

        //接收回送数据
        final byte[] buf = new byte[512];
        DatagramPacket receivePack = new DatagramPacket(buf, buf.length);

        ds.receive(receivePack);

        //打印信息
        String ip = receivePack.getAddress().getHostAddress();
        int port = receivePack.getPort();
        int dataLen = receivePack.getLength();
        String data = new String(receivePack.getData(), 0, dataLen);
        System.out.println("UDPSearcher receive form ip :" + ip + " port:" + port + " data:" + data);

        //完成，关闭
        System.out.println("UDPSearcher Complete.");
        ds.close();
    }
}
